/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentanaEventos2.java
 *
 * Created on 13/01/2012, 06:11:39 AM
 */

package GUI;

import Dominio.Competidor;
import Dominio.Evento;
import Interface.InterfaceEnlace;
import Interface.Motor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.apache.log4j.Logger;


/**
 *
 * @author Patricia
 */
public class VentanaEventos2 extends javax.swing.JFrame {
    private final static Logger log = Logger.getLogger(VentanaEventos2.class);


    private String strTitle = "Eventos-Gamble´s Sport";
    private static InterfaceEnlace miMotor = Motor.getMotorImplementacion();
    private String eventoActual="";
    private String competidorActual="";
    private String pos="";
    private String apuesta="";

    /** Creates new form VentanaEventos2 */
    public VentanaEventos2() {
        
    }

    VentanaEventos2(String nombreEvento) {
        eventoActual = nombreEvento;
        initComponents();
        mostrarTabla();
        

      jTablaEventos.getModel().addTableModelListener(new TableModelListener() {

      public void tableChanged(TableModelEvent e) {
         jTablaEventos.getModel().getValueAt(e.getFirstRow(), e.getColumn());
      }
    });

        
    }


    private void mostrarTabla() {

        DefaultTableModel dm = new DefaultTableModel();
        dm.addColumn("Competidores");
        dm.addColumn("Máxima Apuesta");
        dm.addColumn("Posicion");
        dm.addColumn("Monto a Apostar");
        Evento elEvento = miMotor.buscarEvento(eventoActual);
        ArrayList<Competidor> competidores = new ArrayList<Competidor>();
        competidores = elEvento.getNameCompetitor();
        for (int i=0; i<competidores.size(); i++) {
            Vector row = new Vector();
            row.add(competidores.get(i).getNameCompetitor());
            row.add(competidores.get(i).getMax_amount());
            
            dm.addRow(row);

        }
        
            
         this.jTablaEventos.setModel(dm);
//         if (cont == row.size()){
//            JOptionPane.showMessageDialog(null, "No hay eventos disponibles para esta categoria", strTitle,
//                    JOptionPane.WARNING_MESSAGE);
//        this.dispose();
//        }
        



    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jLabel1 = new javax.swing.JLabel();
        jLayeredPane2 = new javax.swing.JLayeredPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTablaEventos = new javax.swing.JTable();
        jRegresar = new javax.swing.JButton();
        jNick = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/fondo.png"))); // NOI18N
        jLabel1.setBounds(0, 0, 770, 580);
        jLayeredPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLayeredPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Competidores", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
        jPanel3.setOpaque(false);

        jTablaEventos.setFont(new java.awt.Font("Tahoma", 0, 18));
        jTablaEventos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTablaEventos.setRowHeight(40);
        jTablaEventos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTablaEventosMouseReleased(evt);
            }
        });
        jTablaEventos.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jTablaEventosPropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(jTablaEventos);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 665, Short.MAX_VALUE)
                .addGap(23, 23, 23))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE))
        );

        jPanel3.setBounds(20, 120, 710, 340);
        jLayeredPane2.add(jPanel3, javax.swing.JLayeredPane.DRAG_LAYER);

        jRegresar.setText("Regresar");
        jRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRegresarActionPerformed(evt);
            }
        });
        jRegresar.setBounds(480, 570, 130, 50);
        jLayeredPane2.add(jRegresar, javax.swing.JLayeredPane.DRAG_LAYER);

        jNick.setFont(new java.awt.Font("Tahoma", 0, 18));
        jNick.setForeground(new java.awt.Color(204, 255, 255));
        jNick.setBounds(650, 20, 120, 30);
        jLayeredPane2.add(jNick, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton1.setBackground(new java.awt.Color(0, 102, 51));
        jButton1.setFont(new java.awt.Font("Tahoma", 0, 18));
        jButton1.setForeground(new java.awt.Color(255, 255, 255));
        jButton1.setText("Apostar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jButton1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jButton1PropertyChange(evt);
            }
        });
        jButton1.setBounds(243, 471, 170, 60);
        jLayeredPane2.add(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLayeredPane2.setBounds(10, 0, 760, 560);
        jLayeredPane1.add(jLayeredPane2, javax.swing.JLayeredPane.DRAG_LAYER);

        jMenuBar1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 24))); // NOI18N
        jMenuBar1.setFont(new java.awt.Font("Segoe UI", 0, 24));

        jMenu1.setText("Options");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setBackground(new java.awt.Color(255, 255, 255));
        jMenuItem1.setFont(new java.awt.Font("Segoe UI", 0, 24));
        jMenuItem1.setText("Regresar");
        jMenuItem1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jMenuItem1MousePressed(evt);
            }
        });
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 797, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTablaEventosMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTablaEventosMouseReleased
        //         TODO add your handling code here:
         

 

       
}//GEN-LAST:event_jTablaEventosMouseReleased

    private void jRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRegresarActionPerformed
        // TODO add your handling code here:
                VentanaApuestas bienvenida=new VentanaApuestas();
                bienvenida.setVisible(true);
                this.dispose();
}//GEN-LAST:event_jRegresarActionPerformed

    private void jMenuItem1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem1MousePressed
        // TODO add your handling code here:
}//GEN-LAST:event_jMenuItem1MousePressed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        //         TODO add your handling code here:
        VentanaApuestas apuesta = new VentanaApuestas();
        apuesta.setVisible(true);
        this.dispose();
}//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        boolean resultado = false;
        Date fechaMayor;
        Date fechaMenor;
        String Nombre = eventoActual;
        String competidor = competidorActual;
        String posicion = pos;
        String Apuesta = "";
        Evento evento = new Evento();
        evento = miMotor.buscarEvento(Nombre);
        String fechaF = evento.getDate_fin();
        String fechaI = evento.getDate_ini();
        ArrayList<Competidor> competidoresE = new ArrayList<Competidor>();
        competidoresE = evento.getNameCompetitor();
        Date fechaActual = new Date();
        SimpleDateFormat formateador = new SimpleDateFormat("hh:mm:ss");
        formateador.format(fechaActual);
        SimpleDateFormat sdf;
        sdf = new SimpleDateFormat("dd-M-yyyy"  );
        Date fechaFin = null;
        try {
            fechaFin = sdf.parse(fechaF);//Cambio Fecha en Formato DATE
            SimpleDateFormat formateador2 = new SimpleDateFormat("hh:mm:ss");
            formateador2.format(fechaFin);
            fechaFin.setHours(23);
            fechaFin.setMinutes(59);
            fechaFin.setSeconds(00);
        } catch (ParseException ex) {

            log.error("Problemas con la fecha",ex);
        }

        SimpleDateFormat sdf2;
        sdf2 = new SimpleDateFormat("dd-M-yyyy"  );
        Date fechaInicio = null;
        try {
            fechaInicio = sdf2.parse(fechaI);//Cambio Fecha en Formato DATE
            SimpleDateFormat formateador3 = new SimpleDateFormat("hh:mm:ss");
            formateador3.format(fechaInicio);
            fechaInicio.setHours(8);
            fechaInicio.setMinutes(00);
            fechaInicio.setSeconds(00);
        } catch (ParseException ex) {

            log.error("Problemas con la fecha ",ex);
        }

        Map resultadoMap = new HashMap();

       /* Verificamos cual es la mayor de las dos fechas
        */
        //       if (fechaFin.compareTo(fechaActual) > 0){
        fechaMayor = fechaFin;
        fechaMenor = fechaActual;
        //            }else{
        //                fechaMayor = fechaActual;
        //                fechaMenor = fechaFin;
        //            }

        //los milisegundos
        long diferenciaMils = fechaMayor.getTime() - fechaMenor.getTime();

        //obtenemos los segundos
        long segundos = diferenciaMils / 1000;

        //obtenemos las horas
        long horas = segundos / 3600;

        //restamos las horas para continuar con minutos
        segundos -= horas*3600;

        //igual que el paso anterior
        long minutos = segundos /60;
        segundos -= minutos*60;

        //ponemos los resultados en un mapa
        resultadoMap.put("horas",Long.toString(horas));
        resultadoMap.put("minutos",Long.toString(minutos));
        resultadoMap.put("segundos",Long.toString(segundos));


        
        String status="NO ENVIADO";
        for (int i=0; i<competidoresE.size();i++){
            if (competidoresE.get(i).getNameCompetitor().equals(competidor)){
                Apuesta= competidoresE.get(i).getMax_amount();
                if ((Integer.parseInt(Apuesta)> Integer.parseInt(apuesta)) && (Integer.parseInt(apuesta)>0)){
                    resultado=miMotor.agregarApuesta(evento.getName(), evento.getCategoryName(),competidoresE.get(i).getNameCompetitor(), Integer.parseInt(pos), Integer.parseInt(apuesta), fechaActual, status, evento.getCategory_type());
                    if (resultado){
                        JOptionPane.showMessageDialog(this, "Apuesta Agregada",strTitle,JOptionPane.OK_OPTION);

                    }

                } else{
                    JOptionPane.showMessageDialog(this, "Monto Errado: El monto permitido para este competidor debe estar comprendio entre 1 y" + " "+ Apuesta+ " "+ "BsF.",strTitle,JOptionPane.ERROR_MESSAGE);
                }
            }

        }


    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jButton1PropertyChange
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1PropertyChange

    private void jTablaEventosPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTablaEventosPropertyChange
        // TODO add your handling code here:
//        int row = this.jTablaEventos.getSelectedRow();
//         competidorActual= (String) this.jTablaEventos.getModel().getValueAt(row, 0);
//          pos = (String) jTablaEventos.getModel().getValueAt(row, 2);
//          apuesta = (String) jTablaEventos.getModel().getValueAt(row, 3);
        


    }//GEN-LAST:event_jTablaEventosPropertyChange

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaEventos2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JLayeredPane jLayeredPane2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JLabel jNick;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton jRegresar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTablaEventos;
    // End of variables declaration//GEN-END:variables

}
